/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package karelia.webpro.controllers;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import karelia.webpro.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.RequestParam;


/**
 *
 * @author edu100
 */
public class LoginController {
    
    @RequestMapping(value = "/login")
    public void view(){
        
        //return "redirect:login.htm";
    }

    @RequestMapping(value = "/input", method = RequestMethod.POST)
    public String loginUser( @RequestParam(value="email", required=true) String emailAddress,
                        @RequestParam(value="pwd", required=true) String password){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("web-ohj-proj-aaPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Object access;
        try {
        access = em.createNamedQuery("User.findByEmailAndPassword").
                setParameter("email", emailAddress).setParameter("password", password).getSingleResult();    
        } catch(NoResultException e) {
            return "redirect:login.htm";
        }

        em.close();
        emf.close();
        System.out.println("Osoite ja salasana" + emailAddress + "." + password);
        
        if ( access != null ) {//Jos kannasta löytyy sama user ja password
            return "redirect:access.htm";
        } else {
            return "redirect:login.htm";
        }
    }
    
}
